<template>
    <div class="layout">
        <!-- <div class="header-search">
      <el-form :inline="true" :model="formData" class="form-inline">
        <el-form-item style="width: 100%;">
          <el-row :gutter="24" align="middle">
            <el-col :span="12">
              <div style="padding: 10px 0px; font-size: 14px">共{{ tableTotal }}个客户</div>
            </el-col>
            <el-col :span="12" class="right-btn">

            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div> -->
        <ZwSearchForm
            ref="searchFromRef"
            row-num="3"
            :option="searchOption"
            @search="search"
            @reset="reset"
            @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            :row-id-key="activeName == 'cust' ? 'cust_id' : 'groupchat_id'"
            class="table-box"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            :select-all-group="true"
            @selection-change="handleSelectionChange"
            @dataChange="onDataChange"
            @select-all-change="onSelectAllChange"
            @selectAllTotal="selectAllTotal">
            <template #headerOperate>
                <el-popover v-if="isHand" placement="top-start" :width="200" trigger="click">
                    <template>
                        <p>你有{{ handovering }}个移交任务正在处理中，请完成后再操作！</p>
                        <div class="d-flex jc-end">
                            <el-link type="primary" @click="router.push('/channelconfig/dataManagement/asyncTask')">
                                {{ '<查看详情' }}
                            </el-link>
                        </div>
                    </template>
                    <template #reference>
                        <el-button :disabled="disabledBtn()" type="primary" @click="batchTrasfer">
                            {{ activeName == 'cust' ? '批量移交客户' : '批量移交客户群' }}
                        </el-button>
                    </template>
                </el-popover>
                <el-button v-if="!isHand" :disabled="disabledBtn()" type="primary" @click="batchTrasfer">
                    {{ activeName == 'cust' ? '批量移交客户' : '批量移交客户群' }}
                </el-button>
            </template>
        </ZwTable>
        <!--搜索 分配成员 -->
        <ZWDepart ref="DepartRef" @submit="getDeparts" />
        <!--移交 员工-->
        <ZWDepart ref="TrasferRef" :is-local="true" @submit="getTrasfer" />
        <!--弹框-->
        <el-dialog v-model="trasferVisible" custom-class="enterprise_modal" width="500px" draggable>
            <template #title>
                <h4>提示</h4>
            </template>
            <div class="config_title">
                <h4 v-if="selectTableTotal <= 0">
                    将转接{{
                        activeName == 'cust'
                            ? custParams.cust_id_list.length + '位客户'
                            : groupParams.cust_group_id_list.length + '个客户群'
                    }}给{{ custName }}
                </h4>
                <h4 v-else>
                    将转接{{ activeName == 'cust' ? selectTableTotal + '位客户' : selectTableTotal + '个客户群' }}给{{
                        custName
                    }}
                </h4>
                <p>{{ activeName == 'cust' ? '客户' : '客户群' }}将收到以下提示</p>
            </div>
            <div class="config_list">
                <img class="depart_icon" src="/static/service.png" alt="" />
                <div>
                    <p class="config_tag">客服</p>
                    <div class="config_content">
                        您好，您的服务已升级，后续将由我的同事{{ custName }}接替我的工作，继续为您服务。
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="handleTrasfer">确认转接</el-button>
                    <el-button plain @click="cancelTrasfer()">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="tsx" setup>
import { reactive, ref, onMounted, computed, watch } from 'vue';
import ZWTable from '@/components/ZWTable.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import {
    handOverCustAsync,
    handOverCustGroupAsync,
    isHandovering,
    custDetail,
    custGroupDetail
} from '@/api/employe/employeemanage/quit';
import { getSetionId, AFold, tableH } from '@/utils/utils';
import { ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue';
import { deepCopy } from '@/utils/helper';
import { ElMessage, ElAvatar, ElIcon, ElButton } from 'element-plus';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

import router from '@/router';
const props = defineProps(['activeName', 'itemId', 'custData', 'groupData', 'total', 'totalg']);
const DepartRef = ref(null);
const TrasferRef = ref(null);
const searchFromRef = ref<any>(null);
const PaginationRef = ref(null);
const tableRef = ref(null);
const multipleTableRef1 = ref(null);
const multipleTableRef2 = ref(null);
const creators = ref([]);
const times = ref([]);
const tableTotal = ref<number>(0);
const trasferVisible = ref(false);
const custName = ref();
const emit = defineEmits({
    searchData: null,
    close: null
});
const statusList = reactive([
    {
        id: '-1',
        name: '全部'
    },
    {
        id: '0',
        name: '未处理'
    },
    {
        id: '1',
        name: '接替完毕'
    },
    {
        id: '2',
        name: '等待接替'
    },
    {
        id: '3',
        name: '客户拒绝'
    },
    {
        id: '4',
        name: '接替成员客户达到上限'
    },
    {
        id: '20',
        name: '企微推送中'
    }
]);
const formData = reactive({
    id: '',
    keyword: '',
    start_time: '',
    end_time: '',
    assign_ids: [],
    status: -1,
    page: 1,
    page_size: 15
});
const custParams = reactive({
    quit_id: '',
    cust_id_list: [],
    work_user_id_list: [],
    type: 1,
    select_type: 1
});
const groupParams = reactive({
    quit_id: '',
    cust_group_id_list: [],
    work_user_id_list: [],
    type: 1,
    select_type: 1
});
const tableData = ref([]);
const tips = ref();

const custOption = ref([
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        label: '客户信息',
        width: 250,
        render({ row, column, index }) {
            return (
                <div class="cusInfo">
                    <ElAvatar
                        shape="square"
                        size={50}
                        vShow={row.cust_info?.name}
                        class="avatar"
                        src={row.cust_info?.avatar}
                        fit="cover"></ElAvatar>
                    <img vShow={!row.cust_info?.name} src="@/assets/image/account/default_avatar.png" alt=""></img>
                    <span>{row.cust_info?.name}</span>
                    <img class="sex" src={`/static/customer/sex_${row.cust_info?.sex}.png`} alt="" />
                </div>
            );
        }
    },
    {
        prop: 'takeover_status',
        label: '客户状态',
        width: 120,
        render({ row }) {
            return <div>{getStatus(row.takeover_status)}</div>;
        }
    },
    {
        label: '分配员工',
        width: 220,
        render({ row, column, index }) {
            return (
                <>
                    <div vShow={row.wx_processed}> 未知 </div>
                    <div vShow={!row.wx_processed}>
                        <div class="cusInfo" vShow={row.give_work_user_info}>
                            <ElAvatar
                                shape="square"
                                size={50}
                                vShow={row.give_work_user_info?.name}
                                class="avatar"
                                src={row.give_work_user_info?.avatar}
                                fit="cover"></ElAvatar>
                            <img
                                vShow={!row.give_work_user_info?.name}
                                src="@/assets/image/account/default_avatar.png"
                                alt=""></img>
                            <span>{row.give_work_user_info?.name}</span>
                            <img
                                class="sex"
                                src={`/static/customer/sex_${row.give_work_user_info?.gender}.png`}
                                alt=""
                            />
                        </div>
                        <span vShow={!row.give_work_user_info}>--</span>
                    </div>
                </>
            );
        }
    },
    {
        prop: 'takeover_time',
        label: '移交时间',
        width: 200,
        render({ row }) {
            return <div>{row.takeover_time || '--'}</div>;
        }
    },
    {
        prop: 'takeover_status',
        label: '失败原因',
        width: 150,
        render({ row }) {
            return (
                <span>
                    {row.takeover_status == 3 ? '客户拒绝' : row.takeover_status == 3 ? '接替成员客户达到上限' : '--'}
                </span>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 120,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton
                        size="small"
                        vShow={row.takeover_status == 0 || row.status == 0}
                        onClick={() => reSubmit(row)}>
                        分配员工
                    </ElButton>
                </div>
            );
        }
    }
]);
const groupOption = ref([
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        label: '客户群信息',
        width: 250,
        render({ row, column, index }) {
            return (
                <div class="cusInfo" vShow={row.groupchat_info}>
                    <ElAvatar
                        shape="square"
                        size={50}
                        class="avatar"
                        src={row.groupchat_info?.avatar}
                        fit="cover"></ElAvatar>
                    <span>{row.groupchat_info?.name}</span>
                </div>
            );
        }
    },
    {
        prop: 'takeover_status',
        label: '客户群状态',
        width: 120,
        render({ row }) {
            return <span>{getValue(row.status)}</span>;
        }
    },
    {
        label: '分配员工',
        width: 220,
        render({ row, column, index }) {
            return (
                <>
                    <div vShow={row.wx_processed}> 未知 </div>
                    <div vShow={!row.wx_processed}>
                        <div class="cusInfo" vShow={row.work_user_info}>
                            <ElAvatar
                                shape="square"
                                size={50}
                                vShow={row.work_user_info?.name}
                                class="avatar"
                                src={row.work_user_info?.avatar}
                                fit="cover"></ElAvatar>
                            <img
                                vShow={!row.work_user_info?.name}
                                src="@/assets/image/account/default_avatar.png"
                                alt={row.work_user_info?.name}></img>
                            <span>{row.work_user_info?.name}</span>
                            <img class="sex" src={`/static/customer/sex_${row.work_user_info?.gender}.png`} alt="" />
                        </div>
                        <span vShow={!row.work_user_info}>--</span>
                    </div>
                </>
            );
        }
    },
    {
        prop: 'takeover_time',
        label: '移交时间',
        width: 200,
        render({ row }) {
            return <div>{row.takeover_time || '--'}</div>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 120,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton
                        size="small"
                        vShow={row.takeover_status == 0 || row.status == 0}
                        onClick={() => reSubmit(row)}>
                        分配员工
                    </ElButton>
                </div>
            );
        }
    }
]);

const searchOption = computed(() => {
    return [
        {
            label: props.activeName == 'cust' ? '搜索客户' : '搜索客户群',
            name: 'keyword',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入'
        },
        {
            label: '分配成员',
            name: 'assign_ids',
            value: [],
            type: 'select',
            placeholder: '选择成员',
            popperClass: 'zw-hide_select_option',
            multiple: true,
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: props.activeName == 'cust' ? '客户状态' : '分配状态',
            name: 'status',
            value: '-1',
            type: 'select',
            placeholder: '全部',
            optionList: statusList
        },
        {
            label: '分配时间',
            name: 'filter_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const tableOption = computed(() => {
    return props.activeName == 'cust' ? custOption.value : groupOption.value;
});
const getRowKey = (row: any) => {
    return row.id;
};
const defaultParams = reactive({
    id: '', // 明细 id
    keyword: '', // 查询关键字
    assign_ids: [], // 成员参数
    status: -1, // 分配状态
    filter_time: [] // 分配时间
});
const state = reactive({
    searchParams: deepCopy({ ...defaultParams, id: props.itemId })
});
const search = (data: any) => {
    state.searchParams = { ...data, id: props.itemId };
    tableRef.value.clearAllSelect();
    tableRef.value.getTable().clearSelection();
};
const reset = (v?: any) => {
    state.searchParams = { ...v, id: props.itemId };
    tableRef.value.clearAllSelect();
    tableRef.value.getTable().clearSelection();
};
const fetchApi = () => {
    // 获取文件列表
    // getTableH()
    return props.activeName == 'cust' ? custDetail : custGroupDetail;
};
const onDataChange = (data: any) => {
    tableTotal.value = data.total;
};
//获取状态
const getStatus = (type: any) => {
    switch (type) {
        case 0:
            return '未处理';
        case 1:
            return '接替完毕';
        case 2:
            return '等待接替';
        case 3:
            return '客户拒绝';
        case 4:
            return '接替成员客户达到上限';
        case 20:
            return '企微推送中';
    }
};
const getValue = (value: any) => {
    switch (value) {
        case -1:
            return '所有';
        case 0:
            return '未处理';
        case 1:
            return '接替完毕';
        case 2:
            return '等待接替';
        case 3:
            return '接替失败';
    }
};
const visible = ref(true);
const pickUp = () => {
    visible.value = !visible.value;
    AFold(visible.value, '.el_filter_row');
    getTableH();
};
const tabH = ref('400px');
// 表格的自适应高度
const getTableH = () => {
    tabH.value = tableH('.table-box');
};
//查询
const getTableData = () => {
    if (times.value) {
        formData.start_time = times.value[0];
        formData.end_time = times.value[1];
    } else {
        (formData.start_time = ''), (formData.end_time = '');
    }
    emit('searchData', formData);
};
//重新移交
const reSubmit = (val: any) => {
    TrasferRef.value.departVisble = true;
    TrasferRef.value.appDialog.title = '转接给其他成员';
    TrasferRef.value.multiple = false;
    custParams.cust_id_list = [];
    groupParams.cust_group_id_list = [];
    if (props.activeName == 'cust') {
        custParams.cust_id_list.push(val.cust_id);
    } else {
        groupParams.cust_group_id_list.push(val.groupchat_id);
    }
};

// 分页信息
const changeDrawer = (page?: any) => {
    formData.page_size = page ? page.page_size : 1;
    formData.page = page ? page.page : 15;
    getTableData();
};
//清空数据
const clearSearch = (val: any) => {
    if (val == 1) {
        multipleTableRef1.value!.clearSelection();
    } else {
        multipleTableRef2.value!.clearSelection();
    }
    times.value = [];
    (formData.keyword = ''),
        (formData.assign_ids = []),
        (formData.start_time = ''),
        (formData.end_time = ''),
        (formData.status = -1),
        (formData.page = 1),
        (formData.page_size = 15);
    getTableData();
};
//选择成员
const handleImportRole = () => {
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = creators.value;
    //trasferVisible.value = true
};
//获取搜索员工
const getDeparts = (res: any) => {
    creators.value = res;
    formData.assign_ids = getSetionId('id', creators.value);
    DepartRef.value.departVisble = false;
};
//获取移交员工
const getTrasfer = (res: any, val: any) => {
    if (res.length == 0 && !val) {
        ElMessage.error('请选择移交员工！');
        return;
    }
    if (props.activeName == 'cust') {
        custName.value = res[0].name;
        custParams.work_user_id_list = getSetionId('id', res);
    } else {
        custName.value = res[0].name;
        groupParams.work_user_id_list = getSetionId('id', res);
    }
    trasferVisible.value = true;
};
//确认转接
const handleTrasfer = e => {
    if (props.activeName == 'cust') {
        custParams.quit_id = props.itemId;
        if (tableRef.value.getIsSelectAll()) {
            custParams.cust_id_list = cancleAllArray.value;
            custParams.select_type = 2;
        } else {
            custParams.select_type = 1;
        }

        handOverCustAsync({ ...custParams, ...state.searchParams }).then((res: any) => {
            trasferVisible.value = false;
            emit('searchData', formData);
            emit('close');
            parabolaAnimation(e);
            ShowTaskMessage('批量移交客户异步任务创建成功');
        });
    } else {
        groupParams.quit_id = props.itemId;
        if (tableRef.value.getIsSelectAll()) {
            groupParams.cust_group_id_list = cancleAllArray.value;
            groupParams.select_type = 2;
        } else {
            groupParams.select_type = 1;
        }
        handOverCustGroupAsync({ ...groupParams, ...state.searchParams }).then((res: any) => {
            trasferVisible.value = false;
            emit('searchData', formData);
            emit('close');
            parabolaAnimation(e);
            ShowTaskMessage('批量移交客户群异步任务创建成功');
        });
    }
};
//取消转接
const cancelTrasfer = () => {
    trasferVisible.value = false;
};

const selectTableTotal = ref(0);

const selectAllTotal = (value: any) => {
    selectTableTotal.value = value;
};

const cancleAllArray = ref([]);
const onSelectAllChange = (val: any) => {
    cancleAllArray.value = val;
};

//批量选择员工
const handleSelectionChange = (val: any) => {
    if (props.activeName == 'cust') {
        custParams.cust_id_list = getSetionId('cust_id', val);
    } else {
        groupParams.cust_group_id_list = getSetionId('groupchat_id', val);
    }
};
const isHand = ref(false);
const handovering = ref(0);

const getIsHandovering = async () => {
    const res = await isHandovering({ type: props.activeName == 'cust' ? 1 : 2 });
    if (res.handovering == 0) {
        isHand.value = false;
    } else {
        isHand.value = true;
        handovering.value = res.handovering;
    }
};

const disabledBtn = () => {
    if (custParams.cust_id_list.length > 0 || selectTableTotal.value > 0) {
        return false;
    } else {
        return true;
    }
};

//批量移交员工
const batchTrasfer = async () => {
    if (isHand.value) {
        return;
    } else {
        if (props.activeName == 'cust') {
            if (custParams.cust_id_list.length == 0 && selectTableTotal.value <= 0) {
                ElMessage.error('请选择批量移交的客户！');
                return;
            }
        } else {
            if (groupParams.cust_group_id_list.length == 0 && selectTableTotal.value <= 0) {
                ElMessage.error('请选择批量移交的客户群！');
                return;
            }
        }
        TrasferRef.value.departVisble = true;
        TrasferRef.value.multiple = false;
        TrasferRef.value.appDialog.title = '转接给其他成员';
    }
};
//删除员工
const changeDepart = (data: any) => {
    const removeDepart = creators.value.find((item: any) => !data.includes(item.id));
    const arr: any[] = creators.value.filter((item: any) => data.includes(item.id));
    formData.assign_ids = getSetionId('id', arr);
    creators.value = arr;
    DepartRef.value.removeItem(removeDepart);
};

onMounted(() => {
    getIsHandovering();
});
</script>
<style scoped lang="scss">
.d-flex {
    display: flex;
}

.jc-end {
    justify-content: end;
}

.pb-15 {
    padding-bottom: 15px;
}

.layout {
    .header-search {
        margin-bottom: 3px;

        .form-inline {
            display: flex;
            align-items: center;
            padding-bottom: 6px;

            .el-form-item {
                margin-bottom: 0;
            }

            .right-btn {
                padding-right: 0 !important;
                text-align: right;
            }
        }
    }

    .content-search {
        background-color: #f9f9f9;
        padding: 10px 15px;
        margin-bottom: 16px;

        .form-search {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;

            .el-form-item {
                margin-bottom: 22px;
                width: 100%;
            }
        }
    }

    .isMale {
        width: 18px;
        line-height: 18px;
        border-radius: 50%;
        display: inline-block;
        color: #fff;
        background-color: #75ddf4;
        text-align: center;
        margin-left: 5px;
    }

    .isfeMale {
        background-color: #f474bf;
    }

    .config_title {
        text-align: left;
    }

    .config_list {
        background-color: #ebecef;
        width: 100%;
        height: 140px;
        padding-top: 21px;
        display: flex;
        justify-content: center;

        .depart_icon {
            width: 40px;
            height: 40px;
        }

        .config_tag {
            margin-bottom: 3px;
        }

        .config_content {
            padding: 8px;
            line-height: 22px;
            background-color: #fff;
            width: 222px;
            height: 60px;
        }
    }

    .empty {
        height: 400px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        .emty_img {
            transform: translateX(15%);
        }

        .emty_title {
            margin-top: -25px;
        }
    }

    .avatar {
        margin-right: 10px;
        vertical-align: middle;
    }

    .avatar_img {
        width: 50px;
        height: 50px;
        margin-right: 10px;
        vertical-align: middle;
    }

    .cust-status {
        width: 150px;
    }
}

.zw-search-form {
    padding: 16px 16px 0;
    background-color: #f9f9f9;

    .el-row {
        display: flex;
        flex-wrap: wrap;
        position: relative;
        box-sizing: border-box;
        margin: -8px -10px;

        .el-col {
            margin: 8px 0;

            &:last-of-type {
                flex: auto;
                text-align: right;
            }

            .el-form-item {
                margin-bottom: 0;
                width: 100%;

                .el-form-item__label-wrap {
                    .el-form-item__label {
                        font-size: 14px;
                        font-family: STHeitiSC-Light, STHeitiSC;
                        font-weight: 300;
                        color: #33302d;
                    }
                }

                .el-form-item__content {
                    .el-input,
                    .el-select,
                    .el-date-editor {
                        width: 100%;
                    }
                }
            }
        }
    }
}

.sex {
    vertical-align: middle;
    margin-left: 2px;
    width: 18px;
    height: 18px;
}

:deep .el-range-editor.el-input__inner {
    width: 100%;
}

:deep(.cust_info) {
    display: flex;
    align-items: center;
}
</style>
